
<?php
require_once('connection.php');


function createAdminTable(){
	$sql = "CREATE TABLE admin(
			name VARCHAR(100),
			password CHAR(6) NOT NULL,
			PRIMARY KEY(name)
		)";
	if (mysql_query($sql)){
		echo "adminTable created";
	}else{
		echo "adminTable is not created";
		die('Could not create: ' . mysql_error());
	}
}

function clean($str) {
		$str = @trim($str);
		if(get_magic_quotes_gpc()) {
			$str = stripslashes($str);
		}
		return mysql_real_escape_string($str);
}
function insertTuple(){
	$username = clean($_POST['name']);
	$password = clean($_POST['password']);
	$sql="INSERT INTO admin (name, password)
		VALUES('$username','$password')";
	if (!mysql_query($sql)){
		die('Error: ' . mysql_error());
	}else{
		echo "Sign up successful!";
	}
}
function changePassword(){
	session_start();
	$admin_name = clean($_SESSION['SESS_FIRST_NAME']);
	$new_password = clean($_POST['new_password']);
	$sql="UPDATE admin
	      SET admin.password = '$new_password'
		  WHERE admin.name = '$admin_name'";
	if (!mysql_query($sql)){
		die('Error: '.mysql_error());
	}else{
		session_regenerate_id();
		$_SESSION['SESS_FIRST_NAME'] = $admin_name;
		$_SESSION['SESS_LAST_NAME'] = $new_password;
		session_write_close();
	}
}

/*-----------------------Start to execute from this point------------------------------*/

switch($_POST['method'])
{
	case 'insert':
		insertTuple();
		header("location: admin_login.php");
		break;
	case 'delete':
		deleteTuple();
		break;
	case 'change_password':
	    changePassword();
		header("location: admin_Profile.php");
		break;
	DEFAULT:
		echo 'error';
}

?>